# -*- coding: utf-8 -*-

"""
Module implementing mainFrame.
"""
import os, sys
reload(sys)
sys.setdefaultencoding('utf8')
import re
import webbrowser
import ConfigParser

import PyQt4.QtCore, PyQt4.QtGui
from PyQt4.QtCore import pyqtSignature, QStringList, QString
from PyQt4.QtGui import QMainWindow, QStandardItemModel, QStandardItem, QHeaderView

import jieba.analyse
import shelve
from Ui_OPN import Ui_MainWindow

class OPN(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderItem(0, QStandardItem(u'路径'))
        self.model.setHorizontalHeaderItem(1, QStandardItem(u'相关性'))
        self.srView.setModel(self.model)
        self.srView.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
    
    def getRecursiveFile(self, fullPath):
        allFiles = []
        curfiles = os.listdir(fullPath)
        for filename in curfiles:
            filename = filename.decode('gbk').encode('utf-8')
            if filename in ['$RECYCLE.BIN', 'System Volume Information']:
                continue
            if not filename.endswith('_files'):
                fullname = os.path.join(fullPath, filename) 
                allFiles.append(fullname)
                if os.path.isdir(fullname):
                    childFiles = self.getRecursiveFile(fullname)
                    allFiles.append(childFiles)  
        return allFiles
                
    def buildReverseIndex(self, str):
        #预处理
        ss = str.rstrip('.html')
        ss = ss.split('-')[0]
        ss = ''.join(ss.split('\\')[1:])
        ss = ss.replace(' ','')
        ss = ss.lower()  

        keyList = jieba.cut_for_search(ss)
        dbase = shelve.open('db')
        spChars = """~！@#￥%……&*（）——+{}：“|《》？，。、‘；】【=-·~!@#$%^&*()_+}{|":<>?,./;'\][=-`:"""
        spHanZi = u'的'
        for key in keyList:
            if key in spChars or key in spHanZi:
                continue
            key = key.encode('utf-8')
            tmp = dbase.get(key, [])
            if ss not in tmp:
                tmp.append(str)
                dbase[key] = tmp
        dbase.close()
    
    def searchKeys(self,keyList):
        dbase = shelve.open('db')
        num ={}
        for key in keyList:
            key = key.encode('utf-8')
            contList = dbase.get(key, [])
            for cont in contList:
                if cont in num.keys():
                    num[cont] +=1
                else:
                    num[cont] = 1
        sortedKeys = []
        for  key in num.keys():
            start = 0
            end = len(sortedKeys)
            keyCount = num[key]
            while start<end:
                mid = (start+end)/2
                if keyCount>num[sortedKeys[mid]]:
                    end = mid - 1
                else:
                    start = mid + 1
            sortedKeys.insert(start,key)
        return (sortedKeys,num)
    
    @pyqtSignature("")
    def on_quickRefreshBtn_clicked(self):
        """
        Slot documentation goes here.
        """
        print  345
    
    @pyqtSignature("")
    def on_refreshAllBtn_clicked(self):
        """
        Slot documentation goes here.
        """
        dbase = shelve.open('db')
        dbase.clear()
        dbase.close()
        config = ConfigParser.ConfigParser()
        config.read(r'D:\pr_python\OPN\conf.ini')
        try:
            routeStr = config.get('Scan route', 'route')
            routeStr = routeStr.rstrip(';')
            routes = routeStr.split(';')
            for route in routes:
                pageList = self.getRecursiveFile(route)
                print len(pageList)
                for page in pageList:
                    print page
                    self.buildReverseIndex(page)
        except AttributeError,e:
            print e
        
    @pyqtSignature("")
    def on_searchKeyBtn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        self.model.removeRows(0, self.model.rowCount())
        keysText = self.keyEdit.text()
        if keysText == '':
            return
        keysText = unicode(keysText.toUtf8(), 'utf-8', 'ignore')
        keys = jieba.cut_for_search(keysText)
        (sortedKeys, num) = self.searchKeys(keys)
        index =0
        for key in sortedKeys:
            self.model.setItem(index, 0, QStandardItem(key.decode('utf-8')))
            self.model.setItem(index, 1, QStandardItem(str(num[key])))
            index += 1
    
    @pyqtSignature("QModelIndex")
    def on_srView_doubleClicked(self, index):
        """
        Slot documentation goes here.
        """
        url = self.model.data(index).toString()
        webbrowser.open_new_tab(url)
        
if __name__ == '__main__':
    import sys
    app = PyQt4.QtGui.QApplication(sys.argv)
    frame = OPN()
    frame.show()
    sys.exit(app.exec_())
